//
//  XJ_RealNameAuthViewController.m
//  XunJieProject
//
//  Created by xue on 2018/6/11.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_RealNameAuthViewController.h"
#import "XJ_SelectBandView.h"
//相机
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
//相册
#import <AssetsLibrary/AssetsLibrary.h>

#import "XJ_BankListModel.h"
@interface XJ_RealNameAuthViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>{
    
    UIAlertController * phoneAlert;
    NSInteger flag;//1左上 2右上 3 左下 4右下
    NSString * imageUrl1;
    NSString * imageUrl2;
    NSString * imageUrl3;
    NSString * imageUrl4;
    NSMutableArray * imageListArray;
    NSString * bankID;
    dispatch_source_t _timer;
}
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *up_scrollView;
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIView *view4;
@property (weak, nonatomic) IBOutlet UIView *view3;

@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *idNumberTF;
@property (weak, nonatomic) IBOutlet UITextField *despositNumTF;
@property (weak, nonatomic) IBOutlet UITextField *bankNameTF;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UITextField *codeTF;

@property(nonatomic,strong) UIImagePickerController *imagePicker; //声明全局的UIImagePickerController

@property (weak, nonatomic) IBOutlet UIButton *IDHeadButton;
@property (weak, nonatomic) IBOutlet UIButton *IDBackButton;
@property (weak, nonatomic) IBOutlet UIButton *CardHeadButton;
@property (weak, nonatomic) IBOutlet UIButton *CardBackButton;
@property (nonatomic, strong)NSMutableArray * dataArray;
@end

@implementation XJ_RealNameAuthViewController
- (NSMutableArray *)dataArray{
    
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    
    return   _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _codeBtn.layer.cornerRadius = 5;
    _up_scrollView.constant =SafeAreaTopHeight;
    _phoneNumTF.keyboardType =UIKeyboardTypeNumberPad;
    
    [self getBankListData];
    // Do any additional setup after loading the view from its nib.
}
- (IBAction)getCodeAction:(id)sender {
    
    if (_phoneNumTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请填写手机号"];
        return;
    }
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
    [dic setValue:_phoneNumTF.text forKey:@"mobile"];
    [dic setValue:@"3" forKey:@"verifyCodeType"];
    
    [XJ_Utils signPost:@"user/afterSendVerify?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        [self startAnimation];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

-(void)creatMainUI{
    
    self.nav_titleLabel.text =@"实名认证";
    self.nav_rightButton.hidden =NO;
    [self.nav_rightButton setTitle:@"提交" forState:UIControlStateNormal];
    [self.nav_rightButton addTarget:self action:@selector(Click_right) forControlEvents:UIControlEventTouchUpInside];
    
    self.view1.backgroundColor =RGBCOLOR(156, 156, 157);
    self.view2.backgroundColor =RGBCOLOR(156, 156, 157);
    self.view3.backgroundColor =RGBCOLOR(156, 156, 157);
    self.view4.backgroundColor =RGBCOLOR(156, 156, 157);
    self.view1.layer.cornerRadius =4;
    self.view2.layer.cornerRadius =4;
    self.view3.layer.cornerRadius =4;
    self.view4.layer.cornerRadius =4;
    
}

-(void)Click_right{
    
    if (_userNameTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入姓名"];
        return;
    }
    
    if (_idNumberTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入身份证"];
        return;
    }
    
    if (_despositNumTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入储蓄卡号"];
        return;
    }
    
    if (_phoneNumTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    if (_codeTF.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入验证码"];
        return;
    }
    
    if (imageUrl1.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请上传身份证正面"];
        return;
    }
    
    if (imageUrl2.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请上传身份证反面"];
        return;
    }
    
    if (imageUrl3.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请上传银行卡正面"];
        return;
    }
    
    if (imageUrl4.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请上传银行卡反面"];
        return;
    }
    
    imageListArray = [NSMutableArray array];
    
    NSMutableDictionary * imageDic1 = [NSMutableDictionary dictionary];
    [imageDic1 setObject:imageUrl1 forKey:@"url"];
    [imageDic1 setObject:@"101" forKey:@"code"];


    NSMutableDictionary * imageDic2 = [NSMutableDictionary dictionary];
    [imageDic2 setObject:imageUrl2 forKey:@"url"];
    [imageDic2 setObject:@"102" forKey:@"code"];


    NSMutableDictionary * imageDic3 = [NSMutableDictionary dictionary];
    [imageDic3 setObject:imageUrl3 forKey:@"url"];
    [imageDic3 setObject:@"103" forKey:@"code"];


    NSMutableDictionary * imageDic4 = [NSMutableDictionary dictionary];
    [imageDic4 setObject:imageUrl4 forKey:@"url"];
    [imageDic4 setObject:@"104" forKey:@"code"];
    
    
    
    [imageListArray addObject:imageDic1];
    [imageListArray addObject:imageDic2];
    [imageListArray addObject:imageDic3];
    [imageListArray addObject:imageDic4];
    
    [self realNameAuthAction];
}

- (IBAction)Click_btn:(id)sender {
    
    UIButton *button =(UIButton*)sender;
    
    if (button.tag == 0) {
        
        XJ_SelectBandView *alext =[[XJ_SelectBandView alloc]initWithTitle:@"选择发卡银行" cellType:@"0" array:self.dataArray];
        alext.block = ^(id selectValue,id selectValueId ) {
            
            XJ_BankListModel *model =selectValue;
            self->_bankNameTF.text = model.bankName;
            self->bankID = model.bankId;
            
            if (self.dataArray.count>0) {
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:selectValueId];
            }
            
            
        };
        [alext showXLAlertView];
        
    }else{
        
        flag = button.tag;
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择获取图片的方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];

        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            self->_imagePicker = [[UIImagePickerController alloc] init];
            self->_imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            self->_imagePicker.delegate = self;
            self->_imagePicker.allowsEditing = YES;
            [self presentViewController:self->_imagePicker animated:YES completion:nil];
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self->_imagePicker = [[UIImagePickerController alloc] init];
            self->_imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self->_imagePicker.delegate = self;
            self->_imagePicker.allowsEditing = YES;
            self->_imagePicker.navigationBar.translucent = NO;
            [self presentViewController:self->_imagePicker animated:YES completion:nil];
        }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"点击了取消");
        }];
        
        [alert addAction:action1];
        [alert addAction:action2];
        [alert addAction:action3];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    
    [self uploadImage:image];
    
   
    
    
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }

    [dic setValue:[self getCurrentTimestamp] forKey:@"time"];//时间戳
    
    [XJ_Utils imagePost:@"upload/image?" parameters:dic image:image success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        
        if (self->flag == 1) {
            
            self->imageUrl1 = [dataDic objectForKey:@"imageUrl"];
            if (self->imageUrl1) {
                
                [self->_IDHeadButton setImage:image forState:UIControlStateNormal];
            }
                    
        }else if (self->flag == 2){
            
            self->imageUrl2 = [dataDic objectForKey:@"imageUrl"];
            
            if (self->imageUrl2) {
                
                [self->_IDBackButton setImage:image forState:UIControlStateNormal];
            }
            
        }else if(self->flag == 3){
            
            self->imageUrl3 = [dataDic objectForKey:@"imageUrl"];
            
            if (self->imageUrl3) {
                
                [self->_CardHeadButton setImage:image forState:UIControlStateNormal];
            }
            
        }else if (self->flag == 4){
            
            self->imageUrl4 = [dataDic objectForKey:@"imageUrl"];
            
            if (self->imageUrl4) {
                
                [self->_CardBackButton setImage:image forState:UIControlStateNormal];
            }
        }
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}
- (void)realNameAuthAction{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
    [dic setValue:_userNameTF.text forKey:@"userName"];
    [dic setValue:_idNumberTF.text forKey:@"idNumber"];
    [dic setValue:_despositNumTF.text forKey:@"depositCardNo"];
    [dic setValue:bankID forKey:@"bankId"];
    [dic setValue:_phoneNumTF.text forKey:@"mobile"];
    [dic setValue:_codeTF.text forKey:@"verifyCode"];

    
    NSLog(@"dic = %@",dic);
    
    
//    NSError *error;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:imageListArray options:NSJSONWritingPrettyPrinted error:&error];
    
//    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
//    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
//
//    NSString *jsonResult2 = [jsonResult stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    
    [dic setValue:imageListArray.mj_JSONString forKey:@"imageList"];
    NSLog(@"dic = %@",dic);
    
    [XJ_Utils signPost:@"card/verifyPerson?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        if (self.backRefurbishData) {
            self.backRefurbishData();
        }
        
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

-(NSString*)getCurrentTimestamp{
        
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    [formatter setTimeZone:timeZone];
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
        
    
}

- (void)getBankListData{
    
    NSUserDefaults * db = [NSUserDefaults standardUserDefaults];
    NSString * token = [db objectForKey:@"token"];
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:IDENTIFIER forKey:@"equipmentNo"];
    [dic setValue:APPVERSION forKey:@"appVersion"];
    [dic setValue:STSTERMVERSION forKey:@"systemVersion"];
    [dic setValue:USERID forKey:@"userId"];
    
    if (token!=nil &&![token isEqualToString:@""]) {
        
        [dic setValue:token forKey:@"token"];
        
    }
    [dic setValue:@"1" forKey:@"bankType"];
    
    [XJ_Utils signPost:@"user/bankList?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        [self.dataArray removeAllObjects];
        
        NSDictionary * dataDic = [jsonObject objectForKey:@"data"];
        
        NSArray * arr = [dataDic objectForKey:@"bankList"];
        
        if (arr.count > 0) {
            
            for (NSDictionary * dic in arr) {
                
                XJ_BankListModel * bankListModel = [XJ_BankListModel mj_objectWithKeyValues:dic];
                bankListModel.isSelect =NO;
                [self.dataArray addObject:bankListModel];
                
            }
        }
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
}

- (void)startAnimation
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(self->_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self->_codeBtn setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                [self->_codeBtn setBackgroundColor:[UIColor orangeColor]];
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self->_codeBtn setTitle:[NSString stringWithFormat:@"剩余%d秒",seconds] forState:UIControlStateNormal];
                [self->_codeBtn setBackgroundColor:[UIColor grayColor]];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
